package org.wby.jwt.controller;

import com.google.gson.Gson;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wby.jwt.config.props.SecurityProperties;
import org.wby.jwt.dto.UserDTO;
import org.wby.jwt.enums.SecutityEnums;
import org.wby.jwt.po.Token;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
public class LoginController {
    @Autowired
    SecurityProperties securityProperties;

    @PostMapping("/login")
    public Token testLogin(UserDTO userDTO){
        if (userDTO.getUsername().equals("test") && userDTO.getPassword().equals("123456")) {
            Token token = new Token();
            //创建token
            String accessToken = createToken(userDTO,securityProperties.getExp());
            //创建 refreshTocken
            String refreshToken =createToken(userDTO,securityProperties.getExp()*2);

            token.setAccessToken(accessToken);
            token.setRefreshToken(refreshToken);

            return token;
        }else {
            throw new RuntimeException("用户名密码错误");
        }


    }

    private String createToken(UserDTO userDTO,Long expireTime) {
        return Jwts.builder()
                .claim(SecutityEnums.USER_CONTEXT.getValue(), new Gson().toJson(userDTO))
                .subject(userDTO.getUsername())
                .expiration(new Date(System.currentTimeMillis() + expireTime))
                .signWith(Keys.hmacShaKeyFor(securityProperties.getSecKey().getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    @PostMapping("/register")
    public String testRegister(){
        return "333";
    }
}
